$(function(){
	//全局配置
    $.ajaxSetup({
        dataType:"json",
        beforeSend : function() {
            loading.start();
        },
        complete : function() {
            loading.end();
        }
    });
});

//渲染alert
function alert(msg){
    jAlert(msg);
}
//返回上一页
function goBack(){
    history.go(-1);
}
loading={
	start:function(){
		var loadingDiv = "<div id='loadingDiv'>"+
	     "<div style='height: 1325px; display: none; opacity: 0;' class='overlay'></div>"+
	     "<div style='opacity: 0; margin-top: 250px;' id='AjaxLoading' class='showbox'>"+
	     "<div class='loadingWord'>"+
	     "<i class='loader'></i></div></div></div>";
	    var h = $(document).height();
	    $(".overlay").css({ "height": h });
	    var div = $("body").find("#loadingDiv");
	    div.remove();
	    $("body").append($(loadingDiv));
	    $(".overlay").css({ 'display': 'block', 'opacity': '0.2' });
	    $(".showbox").stop(true).animate({ 'margin-top': '200px', 'opacity': '1' }, 200);
	},
	end:function(){
		$(".showbox").stop(true).animate({ 'margin-top': '150px', 'opacity': '0' }, 400);
	    $(".overlay").css({ 'display': 'none', 'opacity': '0' });
	    $("#loadingDiv").remove();
	}

};
//获取地址栏参数组
var getQueryParams = function() {
    var queryString = {};
    var query = window.location.search.substring(1);
    var vars = query.split("&");

    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (typeof queryString[pair[0]] === "undefined") {
            queryString[pair[0]] = decodeURIComponent(pair[1]);
        } else if (typeof queryString[pair[0]] === "string") {
            var arr = [queryString[pair[0]], decodeURIComponent(pair[1])];
            queryString[pair[0]] = arr;
        } else {
            queryString[pair[0]].push(decodeURIComponent(pair[1]));
        }
    }
    return queryString;
};
//获取URL参数
var getQueryParamsByUrl = function(url) {
    var queryString = {};
    var query = url.split('?');
    var vars = '';

    if(query.length === 2){
        query = query[1];
        vars = query.split("&");

        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (typeof queryString[pair[0]] === "undefined") {
                queryString[pair[0]] = decodeURIComponent(pair[1]);
            } else if (typeof queryString[pair[0]] === "string") {
                var arr = [queryString[pair[0]], decodeURIComponent(pair[1])];
                queryString[pair[0]] = arr;
            } else {
                queryString[pair[0]].push(decodeURIComponent(pair[1]));
            }
        }

        return queryString;
    }else{
        return {};
    }
};
//时间转换
var formatTime = function(time, format){ 
    var t = new Date(time * 1000); 
    var tf = function(i){return (i < 10 ? '0' : '') + i;}; 
    return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a){ 
        switch(a){ 
        case 'yyyy': 
            return tf(t.getFullYear()); 
        case 'MM': 
            return tf(t.getMonth() + 1); 
        case 'mm': 
            return tf(t.getMinutes()); 
        case 'dd': 
            return tf(t.getDate());  
        case 'HH': 
            return tf(t.getHours()); 
        case 'ss': 
            return tf(t.getSeconds()); 
        } 
    }); 
};
//获取地址栏单个参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null){
        return unescape(r[2]);
    }else{
        return null;
    }
}
//图片预览
$(document).on('change','.fileImg',function(e){
    $(this).uploadimg(this,e);
});
//上传图片base64
$.fn.uploadimg=function(obj,event){
	var element = event.target,
        files = element.files,
        imgurl;
    if (files) {
        var file = files[0];
        if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(file.name)) {
            alert("图片类型必须是.gif,jpeg,jpg,png中的一种");
            return false;
        }
        if (file.size > 10 * 1024 * 1024) {
            alert("图片不能大于10M");
            return false;
        }
    }
    var reader = new FileReader();
    reader.readAsDataURL(obj.files[0]);
    reader.onload = function (e) {
        imgurl = e.target.result;
        var img = element.nextElementSibling;
        $(obj).next().attr('src', imgurl);
    };
};
//序列化表单
$.fn.getFormparams=function(){
    if (typeof this.serializeArray !== 'undefined') {
       var o = {};    
       var a = this.serializeArray();    
       $.each(a, function() {    
           if (o[this.name]) {    
               if (!o[this.name].push) {    
                   o[this.name] = [o[this.name]];    
               }    
               o[this.name].push(this.value || '');    
           } else {    
               o[this.name] = this.value || '';    
           }    
       });
       return o;
    }
};

//表格功能
var table={
    //删除单个数据
    del:function(a){
        var title=a.msg||'确定要删除该数据？';
        jConfirm(title,'提示框',function(r){
            if(r){
                $.ajax({
                    type:"post",
                    url:a.url,
                    data:{id:a.id}
                }).done(function(data){
                    if(data.Success){
                        jAlert(data.Msg, "提示框", function () {
                            location.reload();
                        });
                    }else{
                        jAlert(data.Msg, "提示框");
                    }
                });
            }
        });
    },
    //删除勾选数据
    delCheck:function(a){
        var title=a.msg||'确定要删除选中数据？';
        if(a.ids.length>0){
            jConfirm(title,'提示框',function(r){
                if(r){
                    $.ajax({
                        type:"post",
                        url:a.url,
                        data:{ids:a.ids}
                    }).done(function(data){
                        if(data.Success){
                            jAlert(data.Msg, "提示框", function () {
                                location.reload();
                            });
                        }else{
                            jAlert(data.Msg, "提示框");
                        }
                    });
                }
            });
        }else{
            alert("必须勾选一项数据！");
        }  
    }
};
//省市区三级联动
var provinceList=function(dom){
    var self=this;
    this.dom=dom;
    this.json=cityJson;
    this.pro=$(dom.find('select')[0]);
    this.city=$(dom.find('select')[1]);
    this.county=$(dom.find('select')[2]);
    this.set=this.getSetting();
    if(this.set!=null){
        this.loadPro(this.set.province);
        this.LoadCity(this.set.city);
        this.LoadCounty(this.set.county);
    }else{
       //加载省
       this.loadPro(); 
    }
    //选择当前，加载下一项
    this.pro.change(function(){
        self.LoadCity();
        self.LoadCounty();
    });
    this.city.change(function(){
        self.LoadCounty();
    });
};
provinceList.prototype={
    //加载省
    loadPro:function(proId){
        this.pro.append(this.readData(this.json));
        if(proId){this.pro.val(proId);}
    },
    //根据省加载市
    LoadCity:function(cityId){
        var proId=this.pro.get(0).selectedIndex,citys=this.json[proId-1];
        if(proId===0){
            this.city.html('<option value="0">--请选择--</option>');
            return false;
        }
        this.city.html(this.readData(citys.cities));
        if(cityId){this.city.val(cityId);}
    },
    //根据市加载区
    LoadCounty:function(countyId){
        var proId=this.pro.get(0).selectedIndex,cityId=this.city.get(0).selectedIndex,citys=this.json[proId-1];
        this.county.html(this.readData(citys.cities[cityId].counties));
        if(countyId){this.county.val(countyId);}
    },
    //渲染数据
    readData:function(data){
        var html='';
        $.each(data,function(index,el){
            html+='<option value="'+el.id+'">'+el.region_name+'</option>';
        });
        return html;
    },
    //获取默认参数
    getSetting:function(){
        var setting=this.dom.attr("rel");
        if(setting&&setting!=="")return $.parseJSON(setting);
        else return null;
    }
};
provinceList.init=function(dom){
    new this(dom);
};
//图片预览放大
// $(".imgPreview").each(function(){
//     var _this=$(this),imgSrc=_this.find('img').attr("src"),imgbox=$('<div class="realImg"><img src='+imgSrc+'></div>');
//     _this.hover(
//         function(){$('body').append(imgbox);},
//         function(){imgbox.remove();}
//     );
// });
















